package cn.melonlib.graphql.model.scalars;

import cn.hutool.core.util.ClassUtil;
import graphql.language.IntValue;
import graphql.language.Value;
import graphql.schema.Coercing;
import graphql.schema.CoercingParseLiteralException;
import graphql.schema.CoercingParseValueException;
import graphql.schema.CoercingSerializeException;

import java.math.BigDecimal;
import java.math.BigInteger;

import static graphql.Assert.assertNotNull;

public class GraphQLBigInt implements Coercing<BigInteger,BigInteger> {


    private BigInteger convertImpl(Object input) {
        if (input instanceof BigInteger number) {
            return number ;
        }else if(input instanceof BigDecimal number){
            return number.toBigInteger();
        }else if(input instanceof Number number){
            return BigInteger.valueOf(number.longValue());
        } else if (input instanceof CharSequence numString) {
            BigDecimal value;
            try {
                value = new BigDecimal(numString.toString());
            } catch (NumberFormatException e) {
                return null;
            }
            try {
                return value.toBigInteger();
            } catch (ArithmeticException e) {
                return null;
            }
        } else {
            return null;
        }
    }

    @Override
    public BigInteger serialize(Object input) {
        BigInteger result = convertImpl(input);
        if (result == null) {
            throw new CoercingSerializeException(
                    "Expected type 'Int' but was '" + ClassUtil.getClassName(input,true) + "'."
            );
        }
        return result;
    }

    @Override
    public BigInteger parseValue(Object input) {
        BigInteger result = convertImpl(input);
        if (result == null) {
            throw new CoercingParseValueException(
                    "Expected type 'Int' but was '" + ClassUtil.getClassName(input,true) + "'."
            );
        }
        return result;
    }

    @Override
    public BigInteger parseLiteral(Object input) {
        if (!(input instanceof IntValue)) {
            throw new CoercingParseLiteralException(
                    "Expected AST type 'IntValue' but was '" + ClassUtil.getClassName(input,true) + "'."
            );
        }
        BigInteger value = ((IntValue) input).getValue();
        return value;
    }

    @Override
    public Value valueToLiteral(Object input) {
        BigInteger result = assertNotNull(convertImpl(input));
        return IntValue.newIntValue(result).build();
    }
}
